<?php

/**
 * This is the model class for table "{{users}}".
 *
 * The followings are the available columns in table '{{users}}':
 * @property integer $id
 * @property string $last_visit
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $role
 * @property string $identity
 * @property string $network
 * @property string $full_name
 * @property string $sex
 * @property integer $avatar
 * @property integer $disabled
 * @property integer $language
 * @property string $address
 * @property string $phone
 * @property string $skype
 * @property string $website
 * @property string $blog
 * @property string $youtube
 * @property integer $country_id
 * @property string $city
 * @property string $birthday
 * @property integer $love_status
 * @property string $status
 * @property string $about
 * @property string $interests
 * @property string $favorite_music
 * @property string $favorite_film
 * @property string $favorite_book
 * @property string $favorite_game
 * @property string $teach
 * @property string $work
 */
class Users extends CActiveRecord
{
	public $oldPassword;
	public $newPassword;
	public $confirmPassword;
	public $oldEmail;
	public $newEmail;
	public $searchName;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Users the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{users}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('first_name, last_name, email', 'required'),
			array('disabled, language, country_id, love_status, wall_my_records, wall_comments, language_profile,
				invitation_group, get_message, view_photo, view_video, view_music,view_info,
				friend_notification, massange_notification, comment_notification, wall_notification, avatar', 'numerical', 'integerOnly'=>true),
			array('username, password, email', 'length', 'max'=>128),
			array('role, identity, network, first_name, last_name, full_name, address, phone, skype, website, blog, youtube, city, status, teach, work', 'length', 'max'=>255),
			array('sex', 'length', 'max'=>1),
			array('about, interests, favorite_music, favorite_film, favorite_book, favorite_game', 'length', 'max'=>1000),
			array('last_visit, birthday, oldPassword, newPassword, confirmPassword', 'safe'),
			array('newEmail', 'email'),
			array('oldPassword', 'unsafe'),
			array('oldPassword', 	'compare', 	'compareValue'=>$this->password, 'allowEmpty'=>true),
			array('newPassword', 	'compare', 	'compareAttribute'=>'confirmPassword'),
			//array('oldEmail', 		'compare', 	'compareValue'=>$this->email, 'allowEmpty'=>true),
			// array('confirmPassword','compare',	'compareAttribute'=>'newPassword'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, last_visit, username, password, email, role, identity, network, first_name, last_name, full_name, sex, avatar, disabled, language, address, phone, skype, website, blog, youtube, country_id, city, birthday, love_status, status, about, interests, favorite_music, favorite_film, favorite_book, favorite_game, teach, work, wall_my_records, wall_comments, language_profile,
				invitation_group, get_message, view_photo, view_video, view_music, view_info,
				friend_notification, massange_notification, comment_notification, wall_notification', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'invite_group'=> array(self::HAS_ONE, 'GroupsUsers', 'user_id',
				'condition'=>'invite_group.invitation=1 AND invite_group.group_id=:group_id',
				'params'=>array(':group_id'=>Yii::app()->request->getParam('group'))
			),	
			'friends'=>array(self::HAS_MANY, 'Friends', 'user_id',
				'condition'=>'friends.status=1',
				'limit' => 6,
				'order' => 'RAND()',
			),					
			'countFriends'=>array(self::STAT, 'Friends', 'user_id',
				'condition'=>'status=1',
			),
			'isFriend'=>array(self::HAS_ONE, 'Friends', 'friend_id',
				'condition'=>'isFriend.user_id=:user_id',
				'params'=>array(':user_id'=>Yii::app()->user->id)
			),
			'isBan'=>array(self::HAS_ONE, 'UsersBlackList', 'ban_id',
				//'condition'=>'usesr_id=:user_id',
				'condition'=>'user_id=:user_id',// && ban_id=:ban_id
				'params'=>array(':user_id'=>Yii::app()->user->id)//Yii::app()->request->getParam('id')
				//'params'=>array(':user_id'=>'1')
			),
			'checkFriend'=>array(self::HAS_ONE,'Friends','user_id',
				'condition'=>'friend_id=:friend_id',
				'params'=>array(':friend_id'=>Yii::app()->user->id)
			),
			'avatar_info'=>array(self::BELONGS_TO, 'Photos', 'avatar'),		
			'albums'=>array(self::HAS_MANY, 'Albums', 'user_id',
				'order' => 'RAND()',
			),
			'countAlbums'=>array(self::STAT, 'Albums', 'user_id'),	
			'countGroups'=>array(self::STAT, 'GroupsUsers', 'user_id'),			
			'videos'=>array(self::HAS_MANY, 'VideoUser', 'user_id',
				'limit' => 10,
				'order' => 'RAND()',
				'condition'=>'videos.status=1'
			),
			'countVideos'=>array(self::STAT, 'VideoUser', 'user_id',
				'condition'=>'status=1'
			),
			'musics'=>array(self::HAS_MANY, 'MusicUser', 'user_id',
				'limit' => 4,
				'order' => 'musics.id DESC',
				'condition'=>'musics.status=1'
			),
			'countMusics'=>array(self::STAT, 'MusicUser', 'user_id',
				'condition'=>'status=1'
			),		
			'comments'=>array(self::HAS_MANY, 'UsersComments', 'profile_id',
				'limit' => 10,
				'order' => 'comments.id DESC',
				'condition'=>'comments.parent_id=0'
			),
			'countComments'=>array(self::STAT, 'UsersComments', 'profile_id'),
			// Страна
			'country'			=>	array(self::BELONGS_TO, 'Country', 'country_id'),	
			'loveStatus'=>	array(self::BELONGS_TO, 'LoveStatus', 'love_status'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' 			=>	'ID',
			'last_visit' 	=>	'Последний визит',
			'username' 		=>	'Username',
			'password' 		=>	'Пароль',
			'oldPassword' 	=>	'Старый пароль',
			'newPassword' 	=>	'Новый пароль',
			'confirmPassword'=>	 'Подвердить пароль',
			'email'			=>	'Email',
			'oldEmail'		=>	'Текущий Email',
			'newEmail'		=>	'Новый Email',
			'role' 			=>	'Role',
			'identity' 		=>	'Identity',
			'network' 		=>	'Network',
			'first_name'	=>	'Имя',
			'last_name'		=>	'Фамилия',
			'full_name' 	=>	'Полное имя',
			'sex' 			=>	'Пол',
			'avatar' 		=>	'Аватар',
			'disabled' 		=>	'Disabled',
			'language' 		=>	'Язык',
			'address' 		=>	'Адрес',
			'phone' 		=>	'Телефон',
			'skype'			=>  'Skype',
			'website'		=>  'Личный сайт',
			'blog'			=>  'Блог',
			'youtube'		=>  'Yоutube канал',	
			'country_id' 	=>	'Страна',
			'city' 			=>	'Город',
			'birthday' 		=>	'Дата рождения',
			'love_status' 	=>	'Семейное положение',
			'status' 		=>	'Статус',
			'about' 		=>	'О себе',
			'interests' 	=>	'Интересы',
			'favorite_music'=>	'Любимая музыка',
			'favorite_film'	=>	'Любимый фильм',		
			'favorite_book'	=>	'Любимые книги',
			'favorite_game'	=>	'Любимые игры',
			'teach' 		=>	'Образование',
			'work' 			=>	'Карьера',
			'wall_my_records'=>	 'Показывать только мои записи',
			'wall_comments' =>	'Отключить комментирование стены',
			'language_profile'=>'Язык',
			'invitation_group'=>'Кто может приглашать меня в сообщества',
			'get_message'=>'Кто может писать мне личные сообщения',
			'view_photo'=>'Кто видит мои фотографии',
			'view_video'=>'Кто видит мои видеозаписи',
			'view_music'=>'Кто может видеть список моих аудиозаписей',
			'view_info'=>'Кому в интернете видна моя страница',
			'friend_notification'=>'Заявки в друзья',
			'massange_notification'=>'Личные сообщения',
			'comment_notification'=>'Ответы в комментариях',
			'wall_notification'=>'Записи на стене',
		);
	}

	public function getUrl()
	{
		return Yii::app()->createUrl('../profile/index',array('id' => $this->id));
	}

	protected function beforeDelete()
	{
		if(parent::beforeDelete())
		{
			Messages::model()->updateAll(
				array('status_from'=>0),
				'`from`=:user_id',
				array(':user_id'=>$this->id)
			);
			Messages::model()->updateAll(
				array('status_to'=>0),
				'`to`=:user_id',
				array(':user_id'=>$this->id)
			);

			Albums::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			EventsComments::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			EventsCommentsLikes::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			EventsUsers::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			Friends::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			Groups::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			GroupsDiscussion::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			GroupsDiscussionComments::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			GroupsDiscussionCommentsLikes::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			GroupsComments::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			GroupsCommentsLikes::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);

			GroupsUsers::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			
			MusicUser::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			Photos::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			PhotosComments::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			PhotosLikes::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			PhotosLikes::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			UsersComments::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			UsersCommentsLikes::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			Video::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			VideoComments::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			VideoLikes::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			VideoUser::model()->deleteAll(
				'user_id=:user_id',
				array(':user_id'=>$this->id)
			);
			return true;
		}
		else
			return false;
	}

	/*protected function beforeSave()
	{
		if(parent::beforeSave())
		{
			if($this->isNewRecord)
			{
				$this->role	= 'user';
			}
			return true;
		}
		else
			return false;
	}*/

	/**
	 * Checks if the given password is correct.
	 * @param string the password to be validated
	 * @return boolean whether the password is valid
	 */
	public function validatePassword($password)
	{
		return $this->hashPassword($password) === $this->password;
	}
	/**
	 * Checks if the given password is correct.
	 * @param string the password to be validated
	 * @return boolean whether the password is valid
	 */
	public function ganaratePassword($password)
	{
		return $this->hashPassword($password);
	}
	/**
	 * Generates the password hash.
	 * @param string password
	 * @param string salt
	 * @return string hash
	 */
	public function hashPassword($password)
	{
		return md5($password);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('last_visit',$this->last_visit,true);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('role',$this->role,true);
		$criteria->compare('identity',$this->identity,true);
		$criteria->compare('network',$this->network,true);
		$criteria->compare('first_name',$this->first_name,true);
		$criteria->compare('last_name',$this->last_name,true);
		$criteria->compare('full_name',$this->full_name,true);
		$criteria->compare('sex',$this->sex,true);
		$criteria->compare('avatar',$this->avatar,true);
		$criteria->compare('disabled',$this->disabled);
		$criteria->compare('language',$this->language);
		$criteria->compare('address',$this->address,true);
		$criteria->compare('phone',$this->phone,true);
		$criteria->compare('skype',$this->skype,true);
		$criteria->compare('website',$this->website,true);
		$criteria->compare('blog',$this->blog,true);
		$criteria->compare('youtube',$this->youtube,true);
		$criteria->compare('country_id',$this->country_id);
		$criteria->compare('city',$this->city,true);
		$criteria->compare('birthday',$this->birthday,true);
		$criteria->compare('love_status',$this->love_status);
		$criteria->compare('status',$this->status,true);
		$criteria->compare('about',$this->about,true);
		$criteria->compare('interests',$this->interests,true);
		$criteria->compare('favorite_music',$this->favorite_music,true);
		$criteria->compare('favorite_film',$this->favorite_film,true);
		$criteria->compare('favorite_book',$this->favorite_book,true);
		$criteria->compare('favorite_game',$this->favorite_game,true);
		$criteria->compare('teach',$this->teach,true);
		$criteria->compare('work',$this->work,true);
		$criteria->compare('wall_my_records',$this->wall_my_records,true);
		$criteria->compare('wall_comments',$this->wall_comments,true);
		$criteria->compare('language_profile',$this->language_profile,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}